package org.dromara.easyes.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ProductName: easy-es
 * Package: org.dromara.easyes.common.utils
 * Description:
 * @Author: 86631561@163.coom
 * Date: 2023/8/1 11:06
 * UpdateUser: 86631561@163.coom
 * UpdateDate: 2023/8/1 11:06
 * UpdateRemark: The modified content
 * Version: 1.0.0
 * <p>
 * Copyright © 2023 86631561@163.coom Technologies Inc. All Rights Reserved
 **/
public class AssemblerUtil {
    private static final String pattern = "\\#\\{[^}]+}";
    public interface Assemble {
        /**
         * 装配过程中需要通过${}里面的表达式找到对应的值
         * @param key ${}里面的表达式
         * @return ${}里面的表达式对应的值
         */
        String getStringByKey(String key);
    }
    /**
     * 装配 ${} 格式的字符串
     * @param str 原始字符串
     * @param assemble 装配过程中获取值的接口
     * @return 装配好之后的字符串
     */
    public static String assemble(String str, Assemble assemble) {
        Pattern r = Pattern.compile(pattern);
        while (true) {
            Matcher m = r.matcher(str);
            if (m.find()) {
                String key = getKey(m.group());
                str = m.replaceFirst(assemble.getStringByKey(key));
            } else {
                break;
            }
        }
        return str;
    }

    /**
     * 获取 ${} 里面的值
     * @param g ${} 表达式
     * @return ${} 里面的值
     */
    public static String getKey(String g) {
        return g.substring(2, g.length() - 1);
    }
}
